package com.tools.scanner.utils

import android.app.Activity
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions
import com.google.mlkit.vision.documentscanner.GmsDocumentScanning
import com.tools.scanner.R

class ScannerPdfUtil {

    companion object {
        fun startScan(
            activity: Activity,
            launcher: ActivityResultLauncher<IntentSenderRequest>,
            limit: Int = 0
        ) {
            val optionsBuilder = GmsDocumentScannerOptions.Builder()
                .setGalleryImportAllowed(true)
                .setScannerMode(GmsDocumentScannerOptions.SCANNER_MODE_FULL)
                .setResultFormats(GmsDocumentScannerOptions.RESULT_FORMAT_JPEG)
            if (limit == 1) {
                optionsBuilder.setPageLimit(1)
            }

            val options = optionsBuilder.build()
            val scanner = GmsDocumentScanning.getClient(options)

            scanner.getStartScanIntent(activity).addOnSuccessListener { intentSender ->
                launcher.launch(IntentSenderRequest.Builder(intentSender).build())
            }.addOnFailureListener { exception ->
                exception.printStackTrace()
                ToastUtil.showToast(R.string.start_fail)
                DataReportUtil.reportOpenPdfFail(exception.toString())
            }
        }
    }
}